package com.vichat.task;

import com.jcraft.jsch.ChannelSftp;
import com.vichat.common.ffmpeg.util.FFMpegUtil;
import com.vichat.common.util.FileTypeUtil;
import com.vichat.common.util.SFtpUtil;
import com.vichat.common.vo.ftp.Ftp;
import com.vichat.res.entity.FtpConfig;
import com.vichat.res.service.ICfgService;
import com.vichat.res.vo.RecFileVO;
import com.vichat.task.service.ITask;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;

/**
 * Created by wangluyin on 2017/9/6.
 * 数据备份
 */
@Component("MediaRecFileDownloadTask")
public class MediaRecFileDownloadTask implements ITask {
    private static transient final Logger logger = LoggerFactory.getLogger(MediaRecFileDownloadTask.class);

    @Autowired
    ICfgService cfgService;

    @Override
    public String doTask(long cfgTaskId) throws Exception {
        List<FtpConfig> ftpConfigs = cfgService.queryFtpConfig();
        for (FtpConfig ftp : ftpConfigs) {
            if ("localhost".equals(ftp.getFtpIp())) {
                scanLocalFtp(ftp);
            } else {
                scanFtp(ftp);
            }
        }
        return "success";
    }

    public void scanFtp(FtpConfig ftp) {
        try {
            Ftp ftpVO = new Ftp();
            ftpVO.setIp(ftp.getFtpIp());
            ftpVO.setUsername(ftp.getFtpName());
            ftpVO.setPassword(ftp.getFtpPass());
            ftpVO.setLocalPath(ftp.getLocalPath());
            ftpVO.setRemotePath(ftp.getRemotePath());
            ftpVO.setPort(ftp.getFtpPort());


            HashMap<String, RecFileVO> recFiles = new HashMap<String, RecFileVO>();
            SFtpUtil sFtpUtil = null;
            try {
                sFtpUtil = new SFtpUtil();
                sFtpUtil.connect(ftp.getFtpIp(), ftp.getFtpName(), ftp.getFtpPass());
                logger.debug("sftp连接成功，开始获取ftp本地目录数据");
                Vector list = sFtpUtil.list(ftp.getRemotePath());
                if (list == null) {
                    return;
                }
                for (Object obj : list) {
                    ChannelSftp.LsEntry lsEntry = (ChannelSftp.LsEntry) obj;
                    String fileName = lsEntry.getFilename();
                    long fileSize = lsEntry.getAttrs().getSize();

                    if (StringUtils.endsWithIgnoreCase(fileName, ".dat") && fileSize > 0) {//是普通文件，且文件不是空文件
                        logger.debug("filename:" + fileName);
                        RecFileVO recFile = getRecFile(fileName);
                        if (recFile != null) {
                            recFile.setFileSize(fileSize);
                            recFiles.put(fileName, recFile);
                            //下载到本地目录
                            if (sFtpUtil.download(ftpVO, ftp.getLocalPath(), ftp.getRemotePath(), recFile.getFileName())) {
                                logger.debug("下载完成，文件名：" + recFile.getFileName());
                            }
                        }
                    }
                }

                File fileFolder = new File(ftp.getLocalPath());
                File[] files = fileFolder.listFiles();
                ;

                for (File file : files) {
                    String fileName = file.getName();
                    long fileSize = file.length();

                    RecFileVO resourceFile = recFiles.get(fileName);
                    //如果大小一致删除资源文件，否则删除本地文件
                    if (resourceFile != null && resourceFile.getFileSize() == fileSize) {
                        sFtpUtil.rm(ftpVO, ftp.getRemotePath(), fileName);
                    } else {
                        file.deleteOnExit();
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                logger.error("录制文件扫描进程处理出错", e);
            } finally {
                if (sFtpUtil != null) {
                    sFtpUtil.close();
                    sFtpUtil = null;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
    }

    public void scanLocalFtp(FtpConfig ftp) {
        try {


            File fileFolder = new File(ftp.getRemotePath());
            if (fileFolder != null && fileFolder.exists()) {
                File[] files = fileFolder.listFiles();
                for (File file : files) {
                    String fileName = file.getName();

                    File remoteFile = new File(ftp.getLocalPath() + "/" + fileName);
                    if (!remoteFile.getParentFile().exists()) {
                        remoteFile.getParentFile().mkdirs();
                    }
                    file.renameTo(remoteFile);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("录制文件扫描进程处理出错", e);
        }

    }

    static RecFileVO getRecFile(String fileName) {
        RecFileVO recFile = new RecFileVO();
        recFile.setFileName(fileName);
        return recFile;
    }


}
